package power

import (
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/power"
	powerReq "github.com/flipped-aurora/gin-vue-admin/server/model/power/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"strconv"
	"strings"
)

type InterviewService struct {
}

// CreateInterview 创建interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) CreateInterview(interview *power.Interview) (err error) {
	fmt.Println("inininininni")
	fmt.Println(interview)
	err = global.GVA_DB.Create(interview).Error
	return err
}

// DeleteInterview 删除interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) DeleteInterview(interview power.Interview) (err error) {
	err = global.GVA_DB.Delete(&interview).Error
	return err
}

// DeleteInterviewByIds 批量删除interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) DeleteInterviewByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]power.Interview{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateInterview 更新interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) UpdateInterview(interview power.Interview) (err error) {
	err = global.GVA_DB.Save(&interview).Error
	return err
}

// GetInterview 根据id获取interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) GetInterview(id uint) (interview power.Interview, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&interview).Error
	return
}

// GetInterviewInfoList 分页获取interview表记录
// Author [piexlmax](https://github.com/piexlmax)
func (interviewService *InterviewService) GetInterviewInfoList(info powerReq.InterviewSearch) (list []power.Interview, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&power.Interview{})
	var interviews []power.Interview
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&interviews).Error
	return interviews, total, err
}

// GetInterviewPower 面试能力图
// func (interviewService *InterviewService) GetInterviewPower(info powerReq.PowerInterView) (Data power.PowerViewInfo, err error) {
func (interviewService *InterviewService) GetInterviewPower(info powerReq.PowerInterView) (Data power.Info, err error) {
	userids := []int{}
	if len(info.UserId) != 0 {
		useridslice := strings.Split(info.UserId, ",")
		for _, v := range useridslice {
			id, _ := strconv.Atoi(v)
			userids = append(userids, id)
		}
	}

	if info.LevelOne == 0 {
		return power.Info{}, status.Error(codes.Internal, "一级分类不能为空")
	}

	if info.ClassId != 0 {
		fmt.Println(info.ClassId)
		err = global.GVA_DB.Table("sys_users").Select("id").Where("class_id=?", info.ClassId).Find(&info.Id).Error
		if err != nil {
			return power.Info{}, status.Error(codes.Internal, err.Error())
		}
	}

	strids := ""
	for k, v := range info.Id {
		if k == len(info.Id)-1 {
			strids = strids + fmt.Sprintf("%d", v)
			break
		}
		strids = strids + fmt.Sprintf("%d,", v)
	}

	selectSQl := ""
	selectClassSQl := ""

	if info.LevelTwo == 0 {
		selectSQl = fmt.Sprintf("SELECT  b.`name`,COUNT(1) AS count FROM interview as a LEFT JOIN interview_type as b ON a.level2 = b.id  where a.level1=%d   GROUP BY b.id,b.`name`", info.LevelOne)
		selectClassSQl = fmt.Sprintf("select u.userid,b.`name` ,count(1)  AS count FROM exercise as u LEFT JOIN  interview_type as b ON u.level_id2=b.id where isok=1 and u.level_id1=%d and u.userid in(%s) GROUP BY b.id,u.userid", info.LevelOne, strids)
		if len(info.UserId) != 0 && info.ClassId == 0 {
			selectClassSQl = fmt.Sprintf("select u.userid,b.`name` ,count(1)  AS count FROM exercise as u LEFT JOIN  interview_type as b ON u.level_id2=b.id where isok=1 and u.level_id1=%d and u.userid in(%s) GROUP BY b.id,u.userid", info.LevelOne, info.UserId)
		}
	} else {
		selectSQl = fmt.Sprintf("SELECT  b.`name`,COUNT(1) AS count FROM interview as a LEFT JOIN interview_type as b ON a.level3 = b.id  where a.level2=%d  GROUP BY b.id", info.LevelTwo)
		selectClassSQl = fmt.Sprintf("select u.userid,b.`name` ,count(1)  AS count FROM exercise as u LEFT JOIN  interview_type as b ON u.level_id3=b.id where isok=1 and u.level_id2=%d and u.userid in(%s) GROUP BY b.id,u.userid", info.LevelTwo, strids)
		if len(info.UserId) != 0 && info.ClassId == 0 {
			selectClassSQl = fmt.Sprintf("select u.userid,b.`name` ,count(1)  AS count FROM exercise as u LEFT JOIN  interview_type as b ON u.level_id3=b.id where isok=1 and u.level_id2=%d and u.userid in(%s) GROUP BY b.id,u.userid", info.LevelTwo, info.UserId)
		}
		fmt.Println(selectSQl)
		fmt.Println(selectClassSQl)
	}

	ti := []power.Ti{}
	err = global.GVA_DB.Table("interview_type").Select("name").Where("pid=? and level=2", info.LevelOne).Find(&ti).Error
	if err != nil {
		return power.Info{}, err
	}

	if info.LevelTwo != 0 {
		err = global.GVA_DB.Table("interview_type").Select("name").Where("pid=? and level=3", info.LevelTwo).Find(&ti).Error
		if err != nil {
			return power.Info{}, err
		}
	}

	//面试题 和总数
	interview := []power.InterviewsNum{}
	uersInfo := []power.UserExpert{}

	err = global.GVA_DB.Raw(selectSQl).Scan(&interview).Error
	err = global.GVA_DB.Raw(selectClassSQl).Scan(&uersInfo).Error
	if err != nil {
		return power.Info{}, status.Error(codes.Internal, err.Error())
	}

	//返回的参数
	info1 := power.Info{}
	indicator := []power.Indicator{}

	//题目和题的数量

	for _, v := range ti {
		i := power.Indicator{
			Name: v.Name,
			Max:  0,
		}
		for _, val := range interview {
			if v.Name == val.Name {
				i.Max = val.Count
			}
		}
		indicator = append(indicator, i)
	}

	info1.Radar.Indicator = indicator

	users := []system.SysUser{}
	err = global.GVA_DB.Where("id in(?)", info.Id).Find(&users).Error

	if len(info.UserId) != 0 && info.ClassId == 0 {
		err = global.GVA_DB.Where("id in (?)", userids).Find(&users).Error
	}

	if err != nil {
		return power.Info{}, err
	}

	usname := []string{}
	for _, v := range users {
		u := v.NickName
		usname = append(usname, u)
	}
	//返回值的用户们
	info1.Legend.Data = usname

	global.GVA_DB.Debug()

	userMap := map[uint]system.SysUser{}

	for _, val := range users {
		userMap[val.ID] = val
	}

	fmt.Println(ti)

	//info1.Title.Text = "power view"
	info1.Title.Text = " "
	series := power.Series{
		Name: " ",
		Type: "radar",
	}
	CountMap := map[string]int{}
	for _, v := range users {
		for _, v := range ti {
			CountMap[v.Name] = 0
		}
		powerInt := []int{}

		for _, val := range uersInfo {
			if val.Userid == int(v.ID) {

				CountMap[val.Name] = val.Count
			}
		}

		for _, v := range ti {
			powerInt = append(powerInt, CountMap[v.Name])
		}
		data := power.Data{
			Value: powerInt,
			Name:  v.NickName,
		}
		data.Lable.Show = true

		series.Data = append(series.Data, data)
	}

	info1.Series = append(info1.Series, series)

	//info1.Radar.Indicator = indicator
	info1.AxisLabel.FontSize = 12
	info1.AxisLabel.Rotate = 60

	return info1, nil
}
